package com.meizhuang.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.base.Strings;
import com.meizhuang.entity.*;
import com.meizhuang.mapper.meizhuang.CircleMapper;
import com.meizhuang.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.meizhuang.base.BaseController;
import com.meizhuang.entity.enums.SystemParameterEnum;
import com.meizhuang.mapper.base.BaseWrapper;
import com.meizhuang.result.JsonResult;
import com.meizhuang.utils.SystemParameterUtils;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;

@RestController
@Api(tags = "首页")
public class IndexController extends BaseController{

	@Autowired
	private OfferProductService offerProductService;
	
	@Autowired
	private LeaveWordService leaveWordService; 
	
	@Autowired
	private UserInfoService userInfoService;
	
	@Autowired
	private ComplaintService complaintService;
	
	@Autowired
	private SearchHistoryService searchHistoryService;
	
	@Autowired
	private ProclamationService proclamationService;
	
	@Autowired
	private AdStationService adStationService;
	
	
	@Autowired
	private HtmlArticleService htmlArticleService;

	@Autowired
	private EntryAuditService entryAuditService;

	@Autowired
	private FollowService followService;

	@Autowired
	private OfferProductLikeService offerProductLikeService;

	@Autowired
	private CircleMapper circleMapper;

	@Autowired
	private OrderService orderService;

	@RequestMapping(value = "/")
	public ModelAndView welcome(HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> retMap = new HashMap<>();
		recommendGate(request, response,retMap);
		return new ModelAndView("home");
	}

	@RequestMapping(value = "/index")
	public JsonResult index(HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> retMap = new HashMap<>();
		recommendGate(request, response,retMap);
		return JsonResult.buildSuccess(retMap);
	}

	private void recommendGate(HttpServletRequest request, HttpServletResponse response,Map retMap) {
		String recommendGateIds = SystemParameterUtils.get(SystemParameterEnum.RECOMMEND_GATE_IDS);
		List<UserInfo> list = new ArrayList<UserInfo>();
		if(!StringUtils.isBlank(recommendGateIds)){
			String[] gateIds = recommendGateIds.split("@");
			for(String id : gateIds){
				if(StringUtils.isNumeric(id)){
					UserInfo userInfo = userInfoService.selectById(Integer.valueOf(id));
					if(userInfo!= null){
						list.add(userInfo);
					}
				}

			}
		}
		if(list.size()>0){
			request.setAttribute("recommend_gate", list);
			retMap.put("recommend_gate", list);
		}

		EntityWrapper<Proclamation> wrapper = new EntityWrapper<Proclamation>();
		wrapper.eq("state", 1);
		wrapper.orderAsc(Arrays.asList("order_num"));
		List<Proclamation> proclamations = proclamationService.selectList(wrapper);
		request.setAttribute("proclamations", proclamations);
		retMap.put("proclamations", proclamations);

		EntityWrapper<AdStation> adWrapper = new EntityWrapper<AdStation>();
		adWrapper.eq("state", 1);
		adWrapper.orderAsc(Arrays.asList("order_num"));
		List<AdStation> adStations = adStationService.selectList(adWrapper);
		request.setAttribute("adstations", adStations);
		retMap.put("adstations", adStations);
		if(adStations.size() >0){
			request.setAttribute("first_adstation", adStations.get(0));
			request.setAttribute("last_adstation", adStations.get(adStations.size() - 1));

			retMap.put("first_adstation", adStations.get(0));
			retMap.put("last_adstation", adStations.get(adStations.size() - 1));
		}
		//1跨境物流  2跑腿代发 3广告跳转 4 其它 5关于我们 
		//6商务合作 7服务条款 8法律声明 9秒换侠  10回收猿  11商家群
		EntityWrapper<HtmlArticle> htmlWrapper = new EntityWrapper<HtmlArticle>();
		htmlWrapper.in("type", 1, 2, 5 ,6 ,7 ,8, 9 ,10 ,11);
		List<HtmlArticle> htmlArticleList = htmlArticleService.selectList(htmlWrapper);

		for(HtmlArticle item : htmlArticleList){
			String url = SystemParameterUtils.get(SystemParameterEnum.HOME_DOMAIN_NAME)+"/h5page/"+item.getId();
			if(item.getType() == 1){//1跨境物流
				request.setAttribute("wuliuUrl", url);
				retMap.put("wuliuUrl", url);
			}else if(item.getType() == 2){//2跑腿代发
				request.setAttribute("daifaUrl", url);
				retMap.put("daifaUrl", url);
			}else if(item.getType() == 5){//5关于我们 
				request.setAttribute("aboutUrl", url);
				retMap.put("aboutUrl", url);
			}else if(item.getType() == 6){//6商务合作
				request.setAttribute("businessUrl", url);
				retMap.put("businessUrl", url);
			}else if(item.getType() == 7){//7服务条款
				request.setAttribute("serviceUrl", url);
				retMap.put("serviceUrl", url);
			}else if(item.getType() == 8){//8法律声明
				request.setAttribute("lawUrl", url);
				retMap.put("lawUrl", url);
			}else if(item.getType() == 9){//9秒换侠
				request.setAttribute("miaohuanUrl", url);
				retMap.put("miaohuanUrl", url);
			}else if(item.getType() == 10){//10回收猿
				request.setAttribute("recycleUrl", url);
				retMap.put("recycleUrl", url);
			}else if(item.getType() == 11){//11商家群
				request.setAttribute("merchantUrl", url);
				retMap.put("merchantUrl", url);
			}
		}


	}

	//搜索
	@RequestMapping(value = "/search")
	public JsonResult search(HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> retMap = new HashMap<>();
		String kw = request.getParameter("kw");



		if(StringUtils.isBlank(kw)){
			retMap.put("msg", "请输入产品关键字");
			return JsonResult.buildError(retMap);
		}
		retMap.put("kw", kw);

		//BaseWrapper<OfferProduct> wrapper = new BaseWrapper<OfferProduct>(OfferProduct.selectFiled, OfferProduct.fromFiled);
		String [] kws = kw.split("\\s+");
		List<String> keys = new ArrayList<String>();
		for(String kItem :kws){
			keys.add(kItem);
			//wrapper.like("offer_product", kItem);
		}
		//wrapper.orderBy("mtime", false);

		//wrapper.last("limit 380");

		List<OfferProduct> listOfferProduct = offerProductService.searchByKey(keys);
		//List<OfferProduct> listOfferProduct = offerProductService.selectByList(wrapper);

		List<OfferProductGroupExt> groupList = new ArrayList<OfferProductGroupExt>();

		for(OfferProduct productItem :listOfferProduct){

			for(String key : kws){
				String replaceProduct = productItem.getOfferProduct().replace(key, "<font style='color:red'>"+key+"</font>");
				productItem.setOfferProduct(replaceProduct);
			}

			OfferProductGroupExt newGroup = new OfferProductGroupExt();
			newGroup.setUid(productItem.getUid());
			newGroup.setRandom(productItem.getRandom());
			newGroup.setMobile(productItem.getMobile());
			newGroup.setWeixin(productItem.getWeixin());
			newGroup.setWeixinImg(productItem.getWeixinImg());
			newGroup.setStoreName(productItem.getStoreName());
			newGroup.setStoreRemark(productItem.getStoreRemark());
			newGroup.setTradeStall(productItem.getTradeStall());
			newGroup.setGatherPrice(productItem.getGatherPrice());


			EntityWrapper<UserInfo> userInfoWrapper = new EntityWrapper();
			userInfoWrapper.eq("uid", productItem.getUid());
			UserInfo userInfo = userInfoService.selectOne(userInfoWrapper);

			if(null != userInfo) {
				newGroup.setLocation(userInfo.getLocation());
				newGroup.setSignature(userInfo.getSignature());
				newGroup.setBackground(userInfo.getBackground());
				newGroup.setLicense(userInfo.getLicense());
			}

//			SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String formatMtime = format.format(productItem.getMtime());
			newGroup.setDate(formatMtime);

//			if(groupList.contains(newGroup)){
//				int indexOf = groupList.indexOf(newGroup);
//				OfferProductGroupExt getGroup = groupList.get(indexOf);
//				List<OfferProduct> groupProducts = getGroup.getProductList();
//				groupProducts.add(productItem);
//			}else{
//				List<OfferProduct>  groupProducts = new ArrayList<OfferProduct>();
//				groupProducts.add(productItem);
//				newGroup.setProductList(groupProducts);
//				groupList.add(newGroup);
//			}
			List<OfferProduct>  groupProducts = new ArrayList<OfferProduct>();
			groupProducts.add(productItem);
			newGroup.setProductList(groupProducts);
			groupList.add(newGroup);

			EntityWrapper<EntryAudit> entryAuditEntityWrapper = new EntityWrapper();
			entryAuditEntityWrapper.eq("uid", productItem.getUid());
			entryAuditEntityWrapper.eq("offer_product_id", productItem.getId());
			EntryAudit entryAudit = entryAuditService.selectOne(entryAuditEntityWrapper);

			if(null != entryAudit) {
				newGroup.setEntryAudit(entryAudit);
			}


			Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
			if(userSession != null){
				EntityWrapper<Follow> followEntityWrapper = new EntityWrapper();
				followEntityWrapper.eq("follow_uid",productItem.getUid());
				followEntityWrapper.eq("uid",userSession);
				Follow follow = followService.selectOne(followEntityWrapper);

				if(null != follow){
					newGroup.setFollow(1);
				}
				EntityWrapper<OfferProductLike> offerProductLikeEntityWrapper = new EntityWrapper();
				offerProductLikeEntityWrapper.eq("uid", userSession);
				offerProductLikeEntityWrapper.eq("offer_product_id",productItem.getId());
				OfferProductLike offerProductLike = offerProductLikeService.selectOne(offerProductLikeEntityWrapper);

				if(null != offerProductLike ){
					newGroup.setLike(1);
				}
			}


		}




		retMap.put("productGroupList", groupList);

		SearchHistory newHistory = new SearchHistory();
		newHistory.setKey(kw.trim());
		newHistory.setIp(getIpAddr(request));
		searchHistoryService.insert(newHistory);

		return JsonResult.buildSuccess(retMap);
	}





	@RequestMapping(value = "/dangkou_goods")
	public JsonResult dangkou_goods(HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> retMap = new HashMap<>();

		String gateId = request.getParameter("gate");
		String random = request.getParameter("random");
		String kw = request.getParameter("kw");

		EntityWrapper<UserInfo> entityWrapper = new EntityWrapper<UserInfo>();
		entityWrapper.eq("uid", gateId);
//		entityWrapper.eq("random", random);
		List<UserInfo> userList = userInfoService.selectList(entityWrapper);

		Date now = new Date();

		List<OfferProduct> offerProducts = new ArrayList<>();

		final long days = 2;

		List<OfferProductGroupExt> groupList = new ArrayList<>();

		if(userList !=null && userList.size()>0) {
			EntityWrapper<OfferProduct> offerWrapper = new EntityWrapper<OfferProduct>();
			offerWrapper = new EntityWrapper<OfferProduct>();
			offerWrapper.eq("uid", gateId);
			offerWrapper.orderBy("ctime", false);
//			offerWrapper.last("limit 0,10000");
//			offerWrapper.last("limit 0,1000");
//			offerWrapper.ge("ctime", new Date(now.getTime() - days * 24 * 60 * 60 * 1000));//最近2天报价
			offerWrapper.last("limit 0,100");
			offerProducts = offerProductService.selectList(offerWrapper);


			Map<String, List<OfferProduct>> mapProducts = new LinkedHashMap<String, List<OfferProduct>>();

			for (OfferProduct product : offerProducts) {
				String fromDate = DateUtil.format(product.getCtime(), DatePattern.NORM_DATETIME_FORMAT);
				List<OfferProduct> maList = mapProducts.get(fromDate);
				if (maList == null) {
					maList = new ArrayList();
					maList.add(product);
					mapProducts.put(fromDate, maList);
				} else {
					maList.add(product);
				}
			}

			retMap.put("mapProducts", mapProducts);
			//request.setAttribute("offerProducts", offerProducts);
			retMap.put("productCount", offerProducts.size());
			retMap.put("user", userList.get(0));


			/*************************************************************************************************************/
			EntityWrapper<UserInfo> userInfoWrapper = new EntityWrapper();
			userInfoWrapper.eq("uid", gateId);
			UserInfo userInfo = userInfoService.selectOne(userInfoWrapper);

			for(OfferProduct productItem :offerProducts){
				OfferProductGroupExt newGroup = new OfferProductGroupExt();
				newGroup.setUid(productItem.getUid());
				newGroup.setRandom(productItem.getRandom());
				newGroup.setMobile(productItem.getMobile());
				newGroup.setWeixin(productItem.getWeixin());
				newGroup.setWeixinImg(productItem.getWeixinImg());
				newGroup.setStoreName(productItem.getStoreName());
				newGroup.setStoreRemark(productItem.getStoreRemark());
				newGroup.setTradeStall(productItem.getTradeStall());
				newGroup.setGatherPrice(productItem.getGatherPrice());

				if(null != userInfo) {
					newGroup.setLocation(userInfo.getLocation());
					newGroup.setSignature(userInfo.getSignature());
					newGroup.setBackground(userInfo.getBackground());
					newGroup.setLicense(userInfo.getLicense());
				}

				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				String formatMtime = format.format(productItem.getMtime());
				newGroup.setDate(formatMtime);

				List<OfferProduct>  groupProducts = new ArrayList<OfferProduct>();
				groupProducts.add(productItem);
				newGroup.setProductList(groupProducts);
				groupList.add(newGroup);

				EntityWrapper<EntryAudit> entryAuditEntityWrapper = new EntityWrapper();
				entryAuditEntityWrapper.eq("uid", productItem.getUid());
				entryAuditEntityWrapper.eq("offer_product_id", productItem.getId());
				EntryAudit entryAudit = entryAuditService.selectOne(entryAuditEntityWrapper);

				if(null != entryAudit) {
					newGroup.setEntryAudit(entryAudit);
				}


				Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
				if(userSession != null){
					EntityWrapper<Follow> followEntityWrapper = new EntityWrapper();
					followEntityWrapper.eq("follow_uid",productItem.getUid());
					followEntityWrapper.eq("uid",userSession);
					Follow follow = followService.selectOne(followEntityWrapper);

					if(null != follow){
						newGroup.setFollow(1);
					}
					EntityWrapper<OfferProductLike> offerProductLikeEntityWrapper = new EntityWrapper();
					offerProductLikeEntityWrapper.eq("uid", userSession);
					offerProductLikeEntityWrapper.eq("offer_product_id",productItem.getId());
					OfferProductLike offerProductLike = offerProductLikeService.selectOne(offerProductLikeEntityWrapper);

					if(null != offerProductLike ){
						newGroup.setLike(1);
					}
				}
			}
			retMap.put("productGroupList", groupList);
			/*************************************************************************************************************/
		}
		return JsonResult.buildSuccess(retMap);
	}
	
	
	
	@RequestMapping(value = "/leaveWord")
	public JsonResult<String> leaveWord(HttpServletRequest request, HttpServletResponse response){
		Integer fromUidInt = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
		String toUid = request.getParameter("uid");
		String leaveWord = request.getParameter("leave_word");
		String key = request.getParameter("key");
		
		if(StringUtils.isBlank(leaveWord)){
			return JsonResult.buildError("留言失败215");
		}
		
		LeaveWord newLeaveWord = new LeaveWord();
		newLeaveWord.setFormUid(fromUidInt);
		newLeaveWord.setToUid(Integer.valueOf(toUid));
		newLeaveWord.setLeaveWord(leaveWord);
		newLeaveWord.setKey(key);
		
		boolean result = leaveWordService.insert(newLeaveWord);
		if(result){
			return JsonResult.buildSuccess();
		}else{
			return JsonResult.buildError("留言失败");
		}
	}
	
	@RequestMapping(value = "/complaint")
	public JsonResult<String> complaint(HttpServletRequest request, HttpServletResponse response){
		Integer fromUidInt = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
		String toUid = request.getParameter("uid");
		String complaint = request.getParameter("complaint");
		String key = request.getParameter("key");
		
		if(StringUtils.isBlank(complaint)){
			return JsonResult.buildError("投诉失败215");
		}
		
		Complaint newComplaint = new Complaint();
		newComplaint.setFormUid(fromUidInt);
		newComplaint.setToUid(Integer.valueOf(toUid));
		newComplaint.setComplaint(complaint);
		newComplaint.setKey(key);
		
		boolean result = complaintService.insert(newComplaint);
		if(result){
			return JsonResult.buildSuccess();
		}else{
			return JsonResult.buildError("投诉失败");
		}
	}
	
	//实时报价动态
	@RequestMapping(value = "/realTimeProduct")
	public JsonResult realTimeProduct(HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> retMap = new HashMap<>();
		BaseWrapper<UserInfo> wrapper = new BaseWrapper<UserInfo>(UserInfo.selectFiled, UserInfo.fromFiled);


		wrapper.isNotNull("product_update_time")
		.groupBy("o.ctime").orderBy("product_update_time", false);
		Date now = new Date();
		final long days = 2;
		wrapper.ge("o.ctime", new Date(now.getTime() - days * 24 * 60 * 60 * 1000).getTime());//最近2天报价
		wrapper.last("limit 200");
		
		List<UserInfo> list = userInfoService.selectByList(wrapper);

		Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

		for(UserInfo userInfo : list){
			
			String fromDate = DateUtil.format(userInfo.getProductUpdateTime(), DatePattern.NORM_DATETIME_PATTERN);
			userInfo.setSctime(fromDate);

			if (null != userSession ) {

				EntityWrapper<Follow> followEntityWrapper = new EntityWrapper();
				followEntityWrapper.eq("follow_uid",userInfo.getUid());
				followEntityWrapper.eq("uid",userSession);
				final Follow follow = followService.selectOne(followEntityWrapper);

				if(null != follow) {
					userInfo.setIsFollow(1); //用户关注了该商户
				}
			}

		}

		retMap.put("list", list);
		return JsonResult.buildSuccess(retMap);
	}

	//留言
	@RequestMapping(value = "/leaveMessage")
	public JsonResult<List<LeaveWordExt>> leaveMessage() {

		Integer uId = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);

		EntityWrapper<LeaveWord> leaveWordEntityWrapper = new EntityWrapper();
		leaveWordEntityWrapper.eq("to_uid",uId);
		List<LeaveWord> leaveWords = leaveWordService.selectList(leaveWordEntityWrapper);

		if(CollectionUtils.isEmpty(leaveWords)){
			return JsonResult.buildSuccess(new ArrayList<>());
		}
		
		EntityWrapper<UserInfo> entityWrapper = new EntityWrapper<UserInfo>();
		entityWrapper.in("uid", leaveWords.stream().map(m->m.getFormUid()).distinct().collect(Collectors.toList()));

		List<UserInfo> userInfoList = userInfoService.selectList(entityWrapper);


		List<LeaveWordExt> collect = leaveWords.stream().map(LeaveWordExt::new).peek(c -> {

			userInfoList.stream().filter(f->f.getUid().intValue() == c.getFormUid().intValue()).findFirst().ifPresent(p->{
				c.setStoreName(p.getStoreName());
				c.setLogoImg(p.getLogoImg());
			});
		}).collect(Collectors.toList());

		return JsonResult.buildSuccess(collect);
	}


	//删除留言
	@RequestMapping(value = "/leaveMessage_delete")
	public JsonResult leaveMessage_delete(HttpServletRequest request, HttpServletResponse response) {

		Map<String,Object> retMap = new LinkedHashMap<>();

		Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
		if(userSession == null){
			retMap.put("msg", "请登录");
			return JsonResult.buildError(retMap);
		}

		String id = request.getParameter("id");

		if(StringUtils.isNotBlank(id)){
			leaveWordService.deleteById(Integer.valueOf(id));
		}

		return JsonResult.buildSuccess(retMap);
	}

	@GetMapping("/keys")
	public JsonResult keys(String key ) {
		String s = SystemParameterUtils.get(SystemParameterEnum.valueOf(key));
		return JsonResult.buildSuccess(s.split("@"));
	}




	//发布商机圈
	@PostMapping(value = "/addCircle",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	@ApiOperation(value = "发布商机圈", notes = "发布商机圈")
	public JsonResult addCircle(HttpServletRequest request, MultipartFile[] pictures,MultipartFile file) {

		Map<String,Object> retMap = new LinkedHashMap<>();
		Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
		if(userSession == null){
			retMap.put("msg", "请登录");
			return JsonResult.buildError(retMap);
		}


		Circle circle = new Circle();
		circle.setText(request.getParameter("text"));
		circle.setUId(userSession.longValue());


		for (MultipartFile multipartFile:pictures) {

			if (!multipartFile.isEmpty()){
				try {
					BufferedImage bi = ImageIO.read(multipartFile.getInputStream());
					if (bi == null) {
						retMap.put("msg", "请上传图片格式的文件");
						return JsonResult.buildError(retMap);
					}
				} catch (IOException e) {
					retMap.put("msg", "请上传图片格式的文件");
					return JsonResult.buildError(retMap);
				}

				String filePath = SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);

				if (org.springframework.util.StringUtils.isEmpty(filePath)) {
					retMap.put("msg", "未配置filePath");
					return JsonResult.buildError(retMap);
				}

				filePath = filePath + File.separator + "circle" + File.separator;

				try {
					InputStream inputStream = multipartFile.getInputStream();
					String fileName = multipartFile.getOriginalFilename();
					Path directory = Paths.get(filePath);
					if (!Files.exists(directory)) {
						Files.createDirectories(directory);
					}
					String newFileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
					Files.copy(inputStream, directory.resolve(newFileName));
					Thumbnails.of(filePath + newFileName).scale(0.7f).toFile(filePath + newFileName);//按比例缩小

					if(org.springframework.util.StringUtils.isEmpty(Strings.nullToEmpty(circle.getImagesUrl()))) {

						circle.setImagesUrl(newFileName);
					}else{

						circle.setImagesUrl(Strings.nullToEmpty(circle.getImagesUrl()) + "|" + newFileName);
					}


				} catch (Exception e) {
					retMap.put("msg", "图片上传失败");
					return JsonResult.buildError(retMap);
				}
			}
		}



		try {

			if (null !=file && !file.isEmpty()) {
				String filePath = SystemParameterUtils.get(SystemParameterEnum.FILE_SAVE_ROOT_PATH);

				filePath = filePath + File.separator + "circle" + File.separator;
				InputStream inputStream = file.getInputStream();
				String fileName = file.getOriginalFilename();
				Path directory = Paths.get(filePath);
				if (!Files.exists(directory)) {
					Files.createDirectories(directory);
				}
				String newFileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
				Files.copy(inputStream, directory.resolve(newFileName));
				circle.setFileUrl(newFileName);
			}

		} catch (Exception e) {
			retMap.put("msg", "文件上传失败");
			return JsonResult.buildError(retMap);
		}


		circleMapper.insert(circle);
		return JsonResult.buildSuccess(retMap);
	}



	//删除发布商机圈
	@DeleteMapping(value = "/circle/{circleId}")
	@ApiOperation(value = "删除商机圈", notes = "删除商机圈")
	public JsonResult deleteCircle(@PathVariable("circleId") String circleId) {
		Map<String,Object> retMap = new LinkedHashMap<>();
		Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
		if(userSession == null){
			retMap.put("msg", "请登录");
			return JsonResult.buildError(retMap);
		}

		circleMapper.deleteById(circleId);
		return JsonResult.buildSuccess(retMap);
	}


	//商机圈列表
	@ApiOperation(value = "商机圈列表", notes = "商机圈列表")
	@GetMapping(value = "/circle")
	public JsonResult circle(HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> retMap = new HashMap<>();

		final String uid = request.getParameter("uid");

		List<Circle> circles ;


		if(StringUtils.isNotBlank(uid)) {

			circles = circleMapper.selectList(new EntityWrapper<Circle>().eq("uId", uid).orderBy("createTime").last("desc"));

		}else{

			circles = circleMapper.selectList(new EntityWrapper<Circle>().orderBy("createTime").last("desc"));
		}

		Optional.ofNullable(circles).ifPresent(c->{

					final List<CircleInfo> circleInfoList = c.stream().map(CircleInfo::new)
							.peek(p -> {
								EntityWrapper<UserInfo> userInfoEntityWrapper = new EntityWrapper<>();
								userInfoEntityWrapper.eq("uid", p.getUId());
								UserInfo userInfo = userInfoService.selectOne(userInfoEntityWrapper);
								p.setUserInfo(userInfo);

								//判断是否是会员
								EntityWrapper<Order> wrapper = new EntityWrapper<>();
								wrapper.eq("uid", p.getUId());
								wrapper.eq("status",2);
								wrapper.orderBy("ctime",false);
								Order order = orderService.selectOne(wrapper);
								if (order != null) {
									p.setVip(true);
								}


							}).collect(Collectors.toList());


					retMap.put("circleList",circleInfoList);
				}

			);

		return JsonResult.buildSuccess(retMap);
	}
}
